/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
 
http://www.cocos2d-x.org

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
package org.cocos2dx.javascript;

//import com.shuxing.chess.wxapi.WXEntryActivity;

import android.app.DownloadManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.cocos.analytics.CAAgent;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import net.sf.json.JSONObject;
import okhttp3.*;
import org.cocos2dx.lib.Cocos2dxActivity;
import org.cocos2dx.lib.Cocos2dxGLSurfaceView;

import java.io.IOException;


public class AppActivity extends Cocos2dxActivity {

    public static IWXAPI wxApi;
    private static boolean wxFlag = true;
    private static String openId;
    private static String nickname;
    private static String avatar;
    private static Integer sex;


    public void regToWx() {
        //IWXAPI 是第三方app和微信通信的openapi接口
        wxApi = WXAPIFactory.createWXAPI(this, Defines.WX_APPID, false);
        //将应用注册到微信
        wxApi.registerApp(Defines.WX_APPID);
    }

    //当这个函数被调用时会弹出微信的登录页面
    public static void loginByWeiXin(int val) {
        //mProgressDialog.show();
        // send oauth request
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_aifuns";
        wxApi.sendReq(req);
    }
    private void getWeiXinAccessToken(String code) {
        //ToastUtil.showShortToast(this,"getWeiXinAccessToken,code:"+code);
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" + "appid=" + Defines.WX_APPID + "&secret=" + Defines.WX_APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        //String url = "http://wwww.baidu.com";
        OkHttpClient okHttpClient = new OkHttpClient();
        Log.d("", "开始请求code");
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("", "onResponse: " + response.body().string());
                try {
                    JSONObject jsonObject = JSONObject.fromObject(response.body().string());
                    String token = jsonObject.optString("access_token");
                    String openId = jsonObject.optString("openid");
                    getWeiXinInfo(token,openId);
                } catch (Exception e) {

                }
            }
        });

//        OkHttpHelper.getinstance().post(this, url, null, new OkHttpBaseCallBack() {
//            @Override
//            public void onRequestBefore() {
//
//            }
//
//            @Override
//            public void onFailure(DownloadManager.Request request, Exception e) {
//                Toast.makeText(instance, "请求微信token失败",Toast.LENGTH_LONG).show();
//            }
//
//            @Override
//            public void onSuccess(Response response, Object o) {
//                try {
//                    JSONObject jsonObject = new JSONObject((String) o);
//                    String token = jsonObject.optString("access_token");
//                    String openId = jsonObject.optString("openid");
//                    getWeiXinInfo(token,openId);
//                } catch (Exception e) {
//
//                }
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, Exception e) {
//
//            }
//        });
    }
    //获取微信名称、头像
    void  getWeiXinInfo(String token,String id){
        String url = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+id;
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求，可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("", "onFailure: ");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Log.d("", "onResponse: " + response.body().string());
                try{
                    JSONObject jsonObject = JSONObject.fromObject(response.body().string());
                    wxFlag = true;
                    openId = jsonObject.optString("openid");
                    nickname = jsonObject.optString("nickname");
                    avatar = jsonObject.optString("headimgurl");
                    sex = jsonObject.optInt("sex");//0:未知 1:男 2:女
                    //mProgressDialog.dismiss();
                }catch (Exception e)
                {

                }
            }
        });

//        OkHttpHelper.getinstance().post(this, url, null, new OkHttpBaseCallBack() {
//            @Override
//            public void onRequestBefore() {
//
//            }
//
//            @Override
//            public void onFailure(Request request, Exception e) {
//
//            }
//
//            @Override
//            public void onSuccess(Response response, Object o) {
//                try{
//                    JSONObject jsonObject = new JSONObject((String) o);
//                    wxFlag = true;
//                    openId = jsonObject.optString("openid");
//                    nickname = jsonObject.optString("nickname");
//                    avatar = jsonObject.optString("headimgurl");
//                    sex = jsonObject.optInt("sex");//0:未知 1:男 2:女
//                    //mProgressDialog.dismiss();
//                }catch (Exception e)
//                {
//
//                }
//
//            }
//
//            @Override
//            public void onError(Response response, int errorCode, Exception e) {
//
//            }
//        });
    }
    //将获取到的值封装成函数以备cocoscreator中调用
    public static boolean getWxFlag(int x){
        return wxFlag;
    }
    public static void setWxFlag(boolean val){wxFlag=val;}
    public static String getOpenId(int x){return openId;}
    public static String getNickname(int x){return nickname;}
    public static String getAvatar(int x){return avatar;}
    public static int getSex(int x){return sex;}

    //闲聊
    // public static ISGAPI sgApi;
    // private static final String xl_APP_ID = "K9o5QIf9GXSdwFO6";
    // private static final String xl_APP_Secret = "rZrlcql3fmHMknDp";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Workaround in https://stackoverflow.com/questions/16283079/re-launch-of-activity-on-home-button-but-only-the-first-time/16447508
        if (!isTaskRoot()) {
            // Android launched another instance of the root activity into an existing task
            //  so just quietly finish and go away, dropping the user back into the activity
            //  at the top of the stack (ie: the last state of this task)
            // Don't need to finish it again since it's finished in super.onCreate .
            return;
        }
        // DO OTHER INITIALIZATION BELOW
        
        SDKWrapper.getInstance().init(this);
        // //初始化api
        regToWx();
        // api = WXAPIFactory.createWXAPI(this,appId);
        // //将应用的appid注册到微信
        // api.registerApp(appId);
        // 通过WXAPIFactory工厂，获取IWXAPI的实例
        // api = WXAPIFactory.createWXAPI(this, APP_ID, true);
        // // 将应用的appId注册到微信
        // api.registerApp(APP_ID);

        CAAgent.enableDebug(false);
    }
    
    @Override
    public Cocos2dxGLSurfaceView onCreateView() {
        Cocos2dxGLSurfaceView glSurfaceView = new Cocos2dxGLSurfaceView(this);
        // TestCpp should create stencil buffer
        glSurfaceView.setEGLConfigChooser(5, 6, 5, 0, 16, 8);

        SDKWrapper.getInstance().setGLSurfaceView(glSurfaceView);

        return glSurfaceView;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SDKWrapper.getInstance().onResume();
        if (CAAgent.isInited()){
            CAAgent.onResume(this);
        }
        if(Defines.resp != null){

            String code = String.valueOf(JSONObject.fromObject(Defines.resp).get("code"));
            getWeiXinAccessToken(code);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        SDKWrapper.getInstance().onPause();
        if (CAAgent.isInited())
            CAAgent.onPause(this);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SDKWrapper.getInstance().onDestroy();
        if (CAAgent.isInited())
            CAAgent.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        SDKWrapper.getInstance().onActivityResult(requestCode, resultCode, data);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        SDKWrapper.getInstance().onNewIntent(intent);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        SDKWrapper.getInstance().onRestart();
    }

    @Override
    protected void onStop() {
        super.onStop();
        SDKWrapper.getInstance().onStop();
    }
        
    @Override
    public void onBackPressed() {
        SDKWrapper.getInstance().onBackPressed();
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        SDKWrapper.getInstance().onConfigurationChanged(newConfig);
        super.onConfigurationChanged(newConfig);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        SDKWrapper.getInstance().onRestoreInstanceState(savedInstanceState);
        super.onRestoreInstanceState(savedInstanceState);
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        SDKWrapper.getInstance().onSaveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onStart() {
        SDKWrapper.getInstance().onStart();
        super.onStart();
    }

}
